//
//  OCRegisterViewController.m
//  League
//
//  Created by JackChen on 2018/2/18.
//  Copyright © 2018年 ciyuanjuzhen. All rights reserved.
//

#import "OCRegisterViewController.h"
#import "ProfileManager.h"
#import "LinkedInHelper.h"
#import "MyProfileViewController.h"
#import "OCProfileViewController.h"

@interface OCRegisterViewController ()

@property (weak, nonatomic) IBOutlet UIButton *areaCodeButton;
@property (weak, nonatomic) IBOutlet UITextField *phoneTextField;
@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;
@property (weak, nonatomic) IBOutlet UITextField *securityCodeTextField;
@property (weak, nonatomic) IBOutlet UIButton *nextButton;
@property (weak, nonatomic) IBOutlet UIButton *securityCodeButton;

@property (nonatomic ,strong) NSTimer *Timer;
@property (strong, nonatomic) NSString *LinkInConfiguration;
@property (assign, nonatomic) NSInteger selectNumIndex;
@property (strong, nonatomic) NSArray *counterNum;
@property (strong, nonatomic) ProfileManager *manager;
@property (strong, nonatomic) NSString *registerCode;
@property (nonatomic ,assign) NSInteger countDown;

@end

@implementation OCRegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"注册";
    self.manager = [ProfileManager shareManager];
    self.selectNumIndex = 0;
    self.counterNum = [NSArray arrayWithObjects:@"+86",@"+852", nil];
    self.view.backgroundColor = sRGBColor(68, 82, 96);
//    self.view.backgroundColor = [UIColor blackColor];
    
    [self setLanguage];
    [self getLinkInConfiguration];
}

- (void)setLanguage {
    NSBundle *bundle = self.languageBundle;
    if (self.state == OCRegister) {
        self.title = [bundle localizedStringForKey:@"regis" value:nil table:@"hello"];
        [self.nextButton setTitle:[bundle localizedStringForKey:@"over" value:nil table:@"hello"] forState:UIControlStateNormal];
    } else {
        self.title =  [bundle localizedStringForKey:@"find" value:nil table:@"hello"];
        [self.nextButton setTitle:[bundle localizedStringForKey:@"Next" value:nil table:@"hello"] forState:UIControlStateNormal];
    }
    [self.securityCodeButton setTitle:[bundle localizedStringForKey:@"getCode" value:nil table:@"hello"] forState:UIControlStateNormal];
    self.phoneTextField.placeholder =[bundle localizedStringForKey:@"PhonePlaceholder" value:nil table:@"hello"];
    self.securityCodeTextField.placeholder =[bundle localizedStringForKey:@"getCode" value:nil table:@"hello"];
    self.passwordTextField.placeholder =[bundle localizedStringForKey:@"PasswordTf" value:nil table:@"hello"];
}

- (void)backStartTime {
    //设置倒计时总时长
    self.securityCodeButton.enabled = NO;
    [self.Timer invalidate];
    self.countDown = 60;
    self.Timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(TimeNSTimer) userInfo:nil repeats:YES];
}

//使用NSTimer实现倒计时
- (void)TimeNSTimer {
    self.countDown --;
    [self.securityCodeButton setTitle:[NSString stringWithFormat:@"%@",@(self.countDown)] forState:UIControlStateNormal];
    if (self.countDown == 0) {
        [self.Timer setFireDate:[NSDate distantFuture]];
        self.securityCodeButton.enabled = YES;
        [InternationalControl initUserLanguage];//初始化应用语言
        NSBundle *bundle = [InternationalControl bundle];
        [self.securityCodeButton setTitle:[bundle localizedStringForKey:@"getCode" value:nil table:@"hello"] forState:UIControlStateNormal];
    }
}

- (void)getLinkInConfiguration {
    NSDictionary *dic = @{
                          @"keyWord":@"LinkedInAuth"
                          };
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",kFirstUrl,kConfigurationUrl];
    NSLog(@"urlStr:%@",urlStr);
    [DataContrller PostRequestUrl:urlStr Param:dic requestSuccess:^(NSDictionary *backDic) {
        NSLog(@"backDic:%@",backDic);
        if ([backDic[@"returnCode"] integerValue] == 200) {
            self.LinkInConfiguration = backDic[@"obj"];
        } else {
            //            [self showAlert:backDic[@"msg"]];
        }
    } requestFail:^(NSString *backErrorStr) {
        NSLog(@"backErrorStr:%@",backErrorStr);
    }];
}

- (void)resetPasswordRequest {
    NSDictionary *dic = @{
                          @"phone":self.phoneTextField.text,
                          @"password":self.passwordTextField.text
                          };
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",kFirstUrl,kResetPassword];
    NSLog(@"urlStr:%@",urlStr);
    [DataContrller PostRequestUrl:urlStr Param:dic requestSuccess:^(NSDictionary *backDic) {
        NSLog(@"backDic:%@",backDic);
        if ([backDic[@"returnCode"] integerValue] == 200) {
            [self.navigationController popViewControllerAnimated:YES];
        } else {
            [self showErrorsWithMessage:backDic];
        }
    } requestFail:^(NSString *backErrorStr) {
        NSLog(@"backErrorStr:%@",backErrorStr);
    }];
}

- (IBAction)nextAction:(UIButton *)sender {
//    self.manager.areaCode = self.counterNum[self.selectNumIndex];
//    self.manager.phone = self.phoneTextField.text;
//    self.manager.password = self.passwordTextField.text;
//    OCProfileViewController *vc = [[OCProfileViewController alloc] init];
//    vc.isRegister = YES;
//    [self.navigationController pushViewController:vc animated:YES];
//    return;
    
    if ([self.phoneTextField.text isEqualToString:@""]) {
        [self showErrorsWithMessage:@"请输入手机号"];
        return;
    }
    if (![self.registerCode isEqualToString:self.securityCodeTextField.text]) {
        [self showErrorsWithMessage:@"验证码错误"];
        return;
    }
    if ([self.passwordTextField.text isEqualToString:@""]) {
        [self showErrorsWithMessage:@"请输入密码"];
        return;
    }
    
    if (self.state == OCForget) {
        [self resetPasswordRequest];
        return;
    }
    
    self.manager.areaCode = self.counterNum[self.selectNumIndex];
    self.manager.phone = self.phoneTextField.text;
    self.manager.password = self.passwordTextField.text;
    
    LinkedInHelper *linkedIn = [LinkedInHelper sharedInstance];
    
    // If user has already connected via linkedin in and access token is still valid then
    // No need to fetch authorizationCode and then accessToken again!
    
    /*
     if (linkedIn.isValidToken) {
     
     linkedIn.customSubPermissions = [NSString stringWithFormat:@"%@,%@", first_name, last_name];
     
     // So Fetch member info by elderyly access token
     [linkedIn autoFetchUserInfoWithSuccess:^(NSDictionary *userInfo) {
     // Whole User Info
     
     NSString * desc = [NSString stringWithFormat:@"first name : %@\n last name : %@", userInfo[@"firstName"], userInfo[@"lastName"] ];
     
     NSLog(@"user Info : %@", userInfo);
     NSLog(@"user Info : %@", desc);
     } failUserInfo:^(NSError *error) {
     NSLog(@"error : %@", error.userInfo.description);
     }];
     } else {
     */
    linkedIn.cancelButtonText = @"Close"; // Or any other language But Default is Close
    NSInteger profile;
    if (self.LinkInConfiguration == nil) {
        profile = BasicProfile;
    } else {
        if ([self.LinkInConfiguration isEqualToString:@"BasicProfile"]) {
            profile = BasicProfile;
        } else {
            profile = FullProfile;
        }
    }
    NSArray *permissions = @[@(profile),
                             @(EmailAddress),
                             @(Share),
                             @(CompanyAdmin)];
    
    linkedIn.showActivityIndicator = YES;
    
#warning - Your LinkedIn App ClientId - ClientSecret - RedirectUrl - And state
    
    [linkedIn requestMeWithSenderViewController:self
                                       clientId:@"81wvfyy9p6hh3z"
                                   clientSecret:@"4BkmGWxEQjIqnG4B"
                                    redirectUrl:@"http://localhost:8080/quick4j/rest/linkedin/getuserinfo"
                                    permissions:permissions
                                          state:@""
                                successUserInfo:^(NSDictionary *userInfo) {
                                    
                                    //                                        self.btnLogout.hidden = !linkedIn.isValidToken;
                                    
                                    NSString * desc = [NSString stringWithFormat:@"first name : %@\n last name : %@",
                                                       userInfo[@"firstName"], userInfo[@"lastName"] ];
                                    NSLog(@"user Info : %@", desc);
                                    
                                    // Whole User Info
                                    NSLog(@"user Info : %@", userInfo);
                                    // You can also fetch user's those informations like below
                                    NSLog(@"job title : %@",     [LinkedInHelper sharedInstance].title);
                                    NSLog(@"company Name : %@",  [LinkedInHelper sharedInstance].companyName);
                                    NSLog(@"email address : %@", [LinkedInHelper sharedInstance].emailAddress);
                                    NSLog(@"Photo Url : %@",     [LinkedInHelper sharedInstance].photo);
                                    NSLog(@"Industry : %@",      [LinkedInHelper sharedInstance].industry);
                                    
                                    ProfileManager *manager = [ProfileManager shareManager];
                                    manager.email = userInfo[@"emailAddress"];
                                    manager.username = userInfo[@"formattedName"];
                                    if (manager.professionsArray == nil) {
                                        manager.professionsArray = [NSMutableArray array];
                                    }
                                    [manager.professionsArray addObject:userInfo[@"headline"] == nil ? @"" : userInfo[@"headline"]];
                                    manager.linkedInAccessToken = userInfo[@"id"];
                                    if (self.state == OCForget) {
                                        [self.navigationController popViewControllerAnimated:YES];
                                    } else {
                                        OCProfileViewController *vc = [[OCProfileViewController alloc] init];
                                        vc.isRegister = YES;
                                        [self.navigationController pushViewController:vc animated:YES];
                                    }
                                } cancelBlock:^{
                                    NSLog(@"User cancelled the request Action");
                                    //                                        self.btnLogout.hidden = NO;
                                } failUserInfoBlock:^(NSError *error) {
                                    NSLog(@"error : %@", error.userInfo.description);
                                    //                                        self.btnLogout.hidden = !linkedIn.isValidToken;
                                }
     ];
    //    }
}

- (IBAction)securityCodeAction:(UIButton *)sender {
    if ([self.phoneTextField.text isEqualToString:@""]) {
        [self showErrorsWithMessage:@"请输入手机号码"];
        return ;
    }
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSDictionary *dic = @{
                          @"phone":self.phoneTextField.text,
                          @"areaNo":self.counterNum[self.selectNumIndex]
                          };
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",kFirstUrl,kRegisterCode];
    NSLog(@"urlStr:%@",urlStr);
    [DataContrller PostRequestUrl:urlStr Param:dic requestSuccess:^(NSDictionary *backDic) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSLog(@"backDic:%@",backDic);
        if ([backDic[@"returnCode"] integerValue] == 200) {
            self.registerCode = backDic[@"obj"][@"phonecode"];
            [self backStartTime];
        } else if ([backDic[@"returnCode"] integerValue] == 404)  {
            [self showErrorsWithMessage:@"手机号码不存在"];
        } else {
            [self showErrorsWithMessage:backDic];
        }
    } requestFail:^(NSString *backErrorStr) {
        NSLog(@"backErrorStr:%@",backErrorStr);
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
}

- (IBAction)areaCodeAction:(UIButton *)sender {
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *_Nonnull action) {
        
    }];
    UIAlertAction *walkingBtn = [UIAlertAction actionWithTitle:@"+86" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        self.selectNumIndex = 0;
        [self.areaCodeButton setTitle:self.counterNum[self.selectNumIndex] forState:UIControlStateNormal];
    }];
    UIAlertAction *gaodeNavigation = [UIAlertAction actionWithTitle:@"+852" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.selectNumIndex = 1;
        [self.areaCodeButton setTitle:self.counterNum[self.selectNumIndex] forState:UIControlStateNormal];
    }];
    
    [alertVc addAction:cancle];
    [alertVc addAction:walkingBtn];
    [alertVc addAction:gaodeNavigation];
    [self presentViewController:alertVc animated:YES completion:nil];
}

@end
